package com.alcatel_lucent.osp.service

import org.apache.commons.io.IOUtils
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import org.springframework.test.context.transaction.TransactionConfiguration
import org.springframework.transaction.annotation.Transactional

import static com.alcatel_lucent.osp.service.JSONServiceImpl.POST_JIRA
import static com.alcatel_lucent.osp.service.JSONServiceImpl.RESOURCE_NAME_KEY

/**
 * Created by guoshunw on 14-3-6.
 */

@Ignore
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = ["/spring.xml"])
@Transactional //Important, or the transaction control will be invalid
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
class JSONServiceTest {

    @Autowired
    private JSONService jsonService;

//    @Test
    void testGetRemoteJSON() throws Exception {
        String strURL = "http://locationinmotion.sinaapp.com/test/DaoServiceTest.php"
//        strURL = "http://localhost:2000"
        URL url = new URL(strURL);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        Map postData = [(RESOURCE_NAME_KEY): POST_JIRA, 'username': 'Guoshun Wu']

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        StringBuilder postDataStr = new StringBuilder();
        for (Map.Entry<String, String> param : postData.entrySet()) {
            if (postDataStr.length() != 0) postDataStr.append('&');
            postDataStr.append(String.format("%s=%s", URLEncoder.encode(param.getKey(), "UTF-8"), URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")));
        }
        byte[] postDataBytes = postDataStr.toString().getBytes("UTF-8");

        connection.connect();

        connection.getOutputStream().write(postDataBytes);


        String resultString = IOUtils.toString(connection.getInputStream());
        println resultString
        connection.disconnect()

//        print jsonService.toString().center(100, '=')
//        def result = jsonService.getRemoteJSON([(RESOURCE_NAME_KEY): POST_JIRA, 'username': 'Guoshun Wu'])
//        println result
    }
}